package org.devops

def deployK8sApp(String CLUSTER_NAME,String appName, String JENKINS_DOCKERFILES_DIR, String VALUES_URL, String IMAGE_PRIFIX,String IMAGE_TAG, String VERSION) {
    withEnv(["KUBECONFIG=/data/k8s_conf/${CLUSTER_NAME}"]) {
        echo "5.1获取项目$appName values.yml文件 "
        withCredentials([string(credentialsId: 'git_root_token', variable: 'git_token')]) {
            sh """rm -f ${JENKINS_DOCKERFILES_DIR}/${appName}-values.yml"""
            echo """values地址: ${VALUES_URL}/values%2F${SERVICE}%2F${appName}%2F${ENV}%2Fvalues.yml/raw?ref=master"""
            sh """
                                        curl -H\"Private-Token: $git_token\" -o\"${JENKINS_DOCKERFILES_DIR}/${appName}-values.yml\" \
                                        \"${VALUES_URL}/values%2F${SERVICE}%2F${appName}%2F${ENV}%2Fvalues.yml/raw?ref=master\"
                                    """
        }


        echo "5.2项目$appName helm 部署"
        String helmName = appName.toLowerCase()
        sh """
            helm upgrade --install --history-max 5 \
            --set image.repository=${IMAGE_PRIFIX} \
            --set image.tag=${IMAGE_TAG} \
            -n ${SERVICE}-${ENV} ${helmName}-${VERSION} \
            -f ${JENKINS_DOCKERFILES_DIR}/${appName}-values.yml \
            xjt/xjt-service \
            --create-namespace
        """
    }
}


def baseNodeDeployK8sApp(String appName, String IMAGE_PRIFIX,String IMAGE_TAG) {
    def response = httpRequest(url: "${Constants.PROJECT_BASE_URL}/jenkins/getJobBuildInfo?mod=${MOD}&job_name=${JOB_NAME}&build_number=${BUILD_NUMBER}", httpMode: 'GET')
    def json = readJSON text: response.content
    if (json.code != 0 ){
        echo response.content
        error "未获取到正确任务编译信息"
    }

    def jobBuildInfo = json.data
    //版本
    def version = jobBuildInfo.version
    //部署集群名
    def deployCluster = jobBuildInfo.deploy_cluster
    //集群连接文件
    def deployClusterConfig = jobBuildInfo.deploy_cluster_config
    //命名空间
    def namespace = jobBuildInfo.namespace
    //helm values。yaml文件
    def deployConfig = jobBuildInfo.deploy_config

    def clusterConfigPath = "${workspace}/.kube/${deployCluster}"
    def helmValuesPath = "${workspace}/.kube/${version}_values.yaml"

    writeFile file: clusterConfigPath, text: "${deployClusterConfig}"
    writeFile file: helmValuesPath, text: "${deployConfig}"

    withEnv(["KUBECONFIG=${clusterConfigPath}"]) {
        echo "5项目$appName helm 部署"
        sh """
            helm upgrade --install --history-max 5 \
            --set image.repository=${IMAGE_PRIFIX} \
            --set image.tag=${IMAGE_TAG} \
            --set app.name=${appName} \
            --set app.version=${version} \
            -n ${namespace} ${appName}-${version} \
            -f ${helmValuesPath} \
            xjt/xjt-service \
            --create-namespace
        """
    }
}

